<template>
  <div class="statistics-container">
    <h2>系统统计数据</h2>

    <!-- 基础统计数据卡片 -->
    <div class="basic-stats">
      <div class="stat-card">
        <div class="stat-icon user-icon"></div>
        <h3>用户总数</h3>
        <p class="stat-value">{{ basicCounts.userCount || 0 }}</p>
        <p class="stat-desc">平台注册用户总量</p>
      </div>
      <div class="stat-card">
        <div class="stat-icon admin-icon"></div>
        <h3>管理员数</h3>
        <p class="stat-value">{{ basicCounts.adminCount || 0 }}</p>
        <p class="stat-desc">系统管理人员数量</p>
      </div>
      <div class="stat-card">
        <div class="stat-icon family-icon"></div>
        <h3>家庭总数</h3>
        <p class="stat-value">{{ basicCounts.familyCount || 0 }}</p>
        <p class="stat-desc">已登记家庭总户数</p>
      </div>
      <div class="stat-card">
        <div class="stat-icon house-icon"></div>
        <h3>房屋总数</h3>
        <p class="stat-value">{{ basicCounts.houseCount || 0 }}</p>
        <p class="stat-desc">已登记房屋总套数</p>
      </div>
    </div>

    <!-- 图表容器 -->
    <div class="charts-grid">
      <!-- 性别比例图表 -->
      <div class="chart-card">
        <h3>居民性别比例</h3>
        <div class="chart-wrapper">
          <div class="pie-container">
            <canvas id="genderPieChart"></canvas>
          </div>
          <div class="legend">
            <div v-for="item in genderRatio" :key="item.type" class="legend-item">
              <span class="legend-color" :style="{ backgroundColor: getGenderColor(item.type) }"></span>
              <span class="legend-text">{{ item.type }}: {{ item.count }} ({{ item.percentage }}%)</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 紧急事务类型比例图表 -->
      <div class="chart-card">
        <h3>紧急事务类型比例</h3>
        <div class="chart-wrapper">
          <div class="pie-container">
            <canvas id="emergencyPieChart"></canvas>
          </div>
          <div class="legend">
            <div v-for="item in emergencyTypeRatio" :key="item.type" class="legend-item">
              <span class="legend-color" :style="{ backgroundColor: getColor(item.type) }"></span>
              <span class="legend-text">{{ item.type }}: {{ item.count }} ({{ item.percentage }}%)</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import Chart from 'chart.js/auto'; // 引入Chart.js

export default {
  name: 'StatisticsDashboard',
  data() {
    return {
      basicCounts: {},
      genderRatio: [],
      emergencyTypeRatio: [],
      genderChart: null,
      emergencyChart: null
    };
  },
  mounted() {
    this.fetchAllStatistics();
  },
  beforeUnmount() {
    // 销毁图表实例，防止内存泄漏
    if (this.genderChart) this.genderChart.destroy();
    if (this.emergencyChart) this.emergencyChart.destroy();
  },
  methods: {
    // 获取所有统计数据
    async fetchAllStatistics() {
      try {
        // 并行请求所有统计接口
        const [
          genderRatioRes,
          emergencyTypeRatioRes,
          basicCountsRes
        ] = await Promise.all([
          axios.get('/api/statistics/gender-ratio'),
          axios.get('/api/statistics/emergency-type-ratio'),
          axios.get('/api/statistics/basic-counts')
        ]);

        this.genderRatio = genderRatioRes.data;
        this.emergencyTypeRatio = emergencyTypeRatioRes.data;
        this.basicCounts = basicCountsRes.data;

        // 数据加载完成后初始化图表
        this.initGenderChart();
        this.initEmergencyChart();
      } catch (error) {
        console.error('获取统计数据失败:', error);
        this.$message.error('加载统计数据失败，请稍后重试');
      }
    },
    // 初始化性别比例饼图
    initGenderChart() {
      const ctx = document.getElementById('genderPieChart').getContext('2d');
      const labels = this.genderRatio.map(item => item.type);
      const data = this.genderRatio.map(item => item.count);
      const colors = this.genderRatio.map(item => this.getGenderColor(item.type));

      this.genderChart = new Chart(ctx, {
        type: 'pie',
        data: {
          labels: labels,
          datasets: [{
            data: data,
            backgroundColor: colors,
            borderWidth: 1,
            borderColor: '#fff'
          }]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          plugins: {
            legend: {
              display: false
            },
            tooltip: {
              callbacks: {
                label: (context) => {
                  const item = this.genderRatio[context.dataIndex];
                  return `${item.type}: ${item.count} (${item.percentage}%)`;
                }
              }
            }
          },
          animation: {
            animateScale: true,
            animateRotate: true
          }
        }
      });
    },
    // 初始化紧急事务类型饼图
    initEmergencyChart() {
      const ctx = document.getElementById('emergencyPieChart').getContext('2d');
      const labels = this.emergencyTypeRatio.map(item => item.type);
      const data = this.emergencyTypeRatio.map(item => item.count);
      const colors = this.emergencyTypeRatio.map(item => this.getColor(item.type));

      this.emergencyChart = new Chart(ctx, {
        type: 'pie',
        data: {
          labels: labels,
          datasets: [{
            data: data,
            backgroundColor: colors,
            borderWidth: 1,
            borderColor: '#fff'
          }]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          plugins: {
            legend: {
              display: false
            },
            tooltip: {
              callbacks: {
                label: (context) => {
                  const item = this.emergencyTypeRatio[context.dataIndex];
                  return `${item.type}: ${item.count} (${item.percentage}%)`;
                }
              }
            }
          },
          animation: {
            animateScale: true,
            animateRotate: true
          }
        }
      });
    },
    // 为不同紧急事务类型设置不同颜色
    getColor(type) {
      const colorMap = {
        '医疗急救': '#e74c3c',    // 红色
        '自然灾害': '#3498db',    // 蓝色
        '安全事故': '#f1c40f',    // 黄色
        '治安事件': '#9b59b6',    // 紫色
        '家庭变故': '#1abc9c',    // 青绿色
        '其他': '#95a5a6'         // 灰色
      };
      return colorMap[type] || '#95a5a6';
    },
    // 性别颜色映射
    getGenderColor(type) {
      const colorMap = {
        '男': '#3498db',   // 蓝色
        '女': '#e74c3c',   // 红色
        '其他': '#9b59b6'  // 紫色
      };
      return colorMap[type] || '#95a5a6';
    }
  }
};
</script>

<style scoped>
.statistics-container {
  padding: 24px;
  max-width: 1400px;
  margin: 0 auto;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.statistics-container h2 {
  color: #2c3e50;
  font-size: 24px;
  margin-bottom: 30px;
  font-weight: 600;
  padding-bottom: 12px;
  border-bottom: 1px solid #e1e4e8;
}

.basic-stats {
  display: flex;
  gap: 24px;
  margin-bottom: 30px;
  flex-wrap: wrap;
}

.stat-card {
  flex: 1;
  min-width: 240px;
  background: #fff;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  text-align: center;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
}

.stat-icon {
  width: 48px;
  height: 48px;
  margin: 0 auto 16px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 20px;
}

.user-icon {
  background-color: #42b983;
}

.admin-icon {
  background-color: #3498db;
}

.family-icon {
  background-color: #f1c40f;
}

.house-icon {
  background-color: #9b59b6;
}

.stat-card h3 {
  color: #666;
  font-size: 16px;
  margin: 0 0 8px;
  font-weight: 500;
}

.stat-value {
  font-size: 32px;
  font-weight: 700;
  color: #2c3e50;
  margin: 0 0 8px;
  line-height: 1.2;
}

.stat-desc {
  font-size: 14px;
  color: #999;
  margin: 0;
}

.charts-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
  gap: 24px;
}

.chart-card {
  background: #fff;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.chart-card h3 {
  color: #2c3e50;
  font-size: 18px;
  margin: 0 0 20px;
  font-weight: 600;
}

.chart-wrapper {
  display: flex;
  align-items: center;
  gap: 20px;
}

.pie-container {
  flex: 1;
  height: 300px;
  position: relative;
}

.legend {
  min-width: 200px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 14px;
}

.legend-color {
  width: 16px;
  height: 16px;
  border-radius: 4px;
  display: inline-block;
}

.legend-text {
  color: #555;
}

/* 响应式调整 */
@media (max-width: 1024px) {
  .charts-grid {
    grid-template-columns: 1fr;
  }

  .chart-wrapper {
    flex-direction: column;
  }

  .legend {
    width: 100%;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: center;
  }
}

@media (max-width: 768px) {
  .basic-stats {
    flex-direction: column;
  }

  .stat-card {
    min-width: auto;
  }

  .pie-container {
    height: 250px;
  }
}
</style>